package com.cm.sys.system.controller;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.cm.sys.framework.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.cm.sys.framework.application.ApiResponseCode;
import com.cm.sys.framework.application.RequestParameter;
import com.cm.sys.framework.application.ResponseResult;
import com.cm.sys.framework.execption.BusinessException;
import com.cm.sys.framework.utils.JsonUtil;
import com.cm.sys.system.entity.User;
import com.cm.sys.system.entity.UserRole;
import com.cm.sys.system.service.UserRoleService;
import com.cm.sys.system.service.UserService;

/**
 * 用户的增删改查
 * 
 * @author yxq18
 *
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    /***
     * 查询用户
     * 
     * @param rp
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public ResponseResult getUser(RequestParameter rp) {

        JSONObject args = rp.getparameters();

        ResponseResult rr = new ResponseResult();

        Map<String, Object> map = userService.selectUsers(args);

        rr.setMap(map);
        return rr;

    }

    /***
     * 查询用户
     * 
     * @param rp
     * @return
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public ResponseResult getUser(RequestParameter rp, @PathVariable("id") String id) {

        ResponseResult rr = new ResponseResult();

        if (StringUtils.isEmpty(id)) {
            throw new BusinessException(ApiResponseCode.CODE_LOGIN.getCode(), "路由错误缺少id");
        }
        User user = userService.selectUser(Integer.parseInt(id));

        rr.setObject(user);

        return rr;

    }

    /***
     * 删除用户
     * 
     * @return
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public ResponseResult deleteUser(RequestParameter rp, @PathVariable("id") String id) {
        ResponseResult rr = new ResponseResult();


        if (StringUtils.isEmpty(id)) {
            throw new BusinessException(ApiResponseCode.CODE_LOGIN.getCode(), "路由错误缺少id");
        }
        //获取当前登录用户
        String token = rp.getToken();
        User user = JwtUtils.validateToken(token);
        //判断当前登录用户id是否与删除的id相同
        if(user.getId() == Integer.parseInt(id)){
            //弹出异常提示，用户不可以删除自己
            throw new BusinessException(ApiResponseCode.NO_DATA.getCode(), "无法自己删除自己账户");
        }
        //判断删除的用户id是否为超级管理员的id，如果是，则拒绝访问
        if(Integer.parseInt(id)== 1){
            throw new BusinessException(ApiResponseCode.NO_DATA.getCode(), "无法删除超级管理员账户");
        }

        //删除用户
        int count = userService.delUser(rp.getparameters(), Integer.parseInt(id));
        //如果用户不存在，删除失败，则不必进行下一步删除user_role的关联操作
        if (count != 1) {
            rr.setCode(ApiResponseCode.NO_DEL_DATA.getCode());
            return rr;
        }
        //删除user_role表中的关联
        int i = userRoleService.deleteByUserId(Integer.parseInt(id));
        return rr;

    }

    /***
     * 更新用户
     * 
     * @param rp
     * @return
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
    public ResponseResult putUser(RequestParameter rp, @PathVariable("id") String id) {
        ResponseResult rr = new ResponseResult();

        if (StringUtils.isEmpty(id)) {
            throw new BusinessException(ApiResponseCode.CODE_LOGIN.getCode(), "路由错误缺少id");
        }
        User user = userService.updateUser(rp.getparameters(), Integer.parseInt(id));
        rr.setObject(user);
        return rr;

    }

    /***
     * 新增用户
     * 
     * @param rp
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult postUser(RequestParameter rp) {
        ResponseResult rr = new ResponseResult();
        JSONObject args = rp.getparameters();
        String userName = JsonUtil.getString(args, "userName");
        String passWord = JsonUtil.getString(args, "password");
        String userRole = JsonUtil.getString(args, "userRole");
        String remake = JsonUtil.getString(args, "remake", "");
        JSONObject json = new JSONObject();
        json.put("userName", userName);
        json.put("password", passWord);
        json.put("userRole", userRole);
        json.put("remake", remake);
        User user = userService.saveUser(json);
        List<UserRole> listUserRole = userService.getUserRole(userRole, user.getId());
        userRoleService.insertBatch(listUserRole);
        rr.setObject(user);
        return rr;

    }

    /***
     * 获取用户的权限
     * 
     * @param rp
     * @return
     */
    @RequestMapping(value = "/getRole", method = RequestMethod.POST)
    public ResponseResult roleUser(RequestParameter rp) {
        ResponseResult rr = new ResponseResult();
        Integer userId = JsonUtil.getInt(rp.getparameters(), "userId");

        List<Integer> roleId = userRoleService.getRoleIdByUserId(userId);
        Map<String, Object> map = new ConcurrentHashMap<String, Object>(16);
        map.put("lists", roleId);
        rr.setMap(map);
        return rr;

    }

}
